import 'dart:async';
import "package:ct_pa_majordomo/config/theme_vars.dart";
import "package:ct_pa_majordomo/pages/device/electricity_meter/api.dart";
import "package:ct_pa_majordomo/utils/event_bus.dart";
import "package:flutter/material.dart";
import "package:flutter_easyloading/flutter_easyloading.dart";

import "sections/meter_info.dart";
import "sections/operation.dart";

class Detail extends StatefulWidget {
  final int electricityMeterId;
  const Detail({super.key, required this.electricityMeterId});

  @override
  State<Detail> createState() => _DetailState();
}

class _DetailState extends State<Detail> {
  Map _info = {};
  late StreamSubscription _subscription;

  Future<void> _getElectricityMeterInfo() async {
    Map resData = await electricityMeterApi.getElectricityMeterInfo(widget.electricityMeterId);
    setState(() {
      _info = resData["data"] ?? {};
    });
  }

  Future<void> _syncOnce() async {
    EasyLoading.show();
    Map<String, dynamic> params = { "id": widget.electricityMeterId };
    await electricityMeterApi.syncOnce(params);
    EasyLoading.dismiss();
    EasyLoading.showToast("更新成功");
    _getElectricityMeterInfo();
  }

  // 处理电表名称更新事件
  void _handleElectricityMeterEvent(ElectricityMeterEvent event) {
    if (event.type == "nameChanged" || event.type == "refreshInfo") {
      // 如果是当前电表的名称更新事件
      if (event.data["electricityMeterId"] == widget.electricityMeterId) {
        _getElectricityMeterInfo();
      }
    }
  }

  @override
  void initState() {
    _getElectricityMeterInfo();
    
    // 订阅电表事件
    _subscription = eventBus.on.listen((event) {
      if (event is ElectricityMeterEvent) {
        _handleElectricityMeterEvent(event);
      }
    });
    
    super.initState();
  }
  
  @override
  void dispose() {
    // 取消订阅
    _subscription.cancel();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        iconTheme: const IconThemeData(color: Colors.white),
        title: Text(_info["name"] ?? "", style: const TextStyle(color: Colors.white),),
        centerTitle: true,
        backgroundColor: ThemeVars.colorPrimary,
        leading: IconButton(
          icon: const Icon(Icons.arrow_back_ios_new),
          onPressed: () {
            Navigator.pop(context);
          },
        ),
        actions: [
          TextButton(
            onPressed: () {
              _syncOnce();
            },
            child: const Text("更新", style: TextStyle(color: Colors.white, fontSize: 16),)
          )
        ],
      ),
      body: ListView(
        padding: const EdgeInsets.symmetric(horizontal: ThemeVars.paddingPage, vertical: 20),
        children: [
          MeterInfo(
            info: _info,
            onChange: (bool value) {
              print("触发函数》》》》》》》》》》》》$value");
              if (value) {
                _getElectricityMeterInfo();
              }
            },
          ),
          const SizedBox(height: 15,),
          Operation(info: _info,),
        ],
      ),
    );
  }

}